package com.zjp.blog.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjp.blog.client.CategoryMapper;
import com.zjp.blog.controller.PagerBean;
import com.zjp.blog.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */

@Service
public class CategoryService
{
    @Autowired
    CategoryMapper categoryMapper;

    public PagerBean<Category> getPage(PagerBean<Category> pager)
    {
        PageHelper.startPage(pager.getPageNum(), pager.getLength());
        List<Category> categories = categoryMapper.selectAll();

        PageInfo pageInfo = new PageInfo(categories);

        pager.setPages(pageInfo.getPages());
        pager.setRecords(categories);

        return pager;
    }

    public PagerBean<Category> getPage(String name,PagerBean pager)
    {
        PageHelper.startPage(pager.getPageNum(), pager.getLength());
        List<Category> categories = searchByName(name);

        PageInfo pageInfo = new PageInfo(categories);

        pager.setPages(pageInfo.getPages());
        pager.setRecords(categories);

        return pager;
    }

    public Category create(Category category)
    {
        category.setCreateTime(new Date());
        category.setUpdateTime(category.getCreateTime());
        categoryMapper.insert(category);
        return category;
    }

    public Category update(Category category)
    {
        category.setUpdateTime(new Date());
        categoryMapper.updateByPrimaryKeySelective(category);
        return category;
    }

    public int deleteById(Integer id)
    {
        int count=0;
        count += categoryMapper.deleteByPrimaryKey(id);
        return count;
    }

    public List<Category> searchByName(String name)
    {
        name = "%" + name + "%";
        return categoryMapper.searchByName(name);
    }

    public Category getByName(String name)
    {
        return categoryMapper.selectByName(name);
    }

    public Category getById(Integer id)
    {
        return categoryMapper.selectByPrimaryKey(id);
    }

    public List<Category> getAll()
    {
        return categoryMapper.selectAll();
    }

}
